package com.dzqc.j2cache;

import net.oschina.j2cache.CacheChannel;
import net.oschina.j2cache.CacheObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/j2cache")
public class J2CacheController {
    private String key="mykey";
    private String rx="rx";

    @Autowired
    private CacheChannel cacheChannel;

    @GetMapping("/getValue")
    public  String getValue(){
       CacheObject cacheObject= cacheChannel.get(rx,key);
       if(cacheObject.getValue()==null){
           //从缓存中娶不到值，我们从数据库去查询
           String dbString = "数据库的值";
           //放入缓存当中
           cacheChannel.set(rx,key,dbString);
           return dbString;
       }
       return  cacheObject.getValue().toString();
    }

    @GetMapping("/getValue1")
    public  String getValue1(){
        CacheObject cacheObject= cacheChannel.get(rx,key);
        return  cacheObject.getValue().toString();
    }
    //一级缓存和二级缓存都会清理
    @GetMapping("/evict")
    public String evict(){
        cacheChannel.evict(rx,key);
        return "evict sussese";
    }

    //清理指定区域
    @GetMapping("/clear")
    public String clear(){
        cacheChannel.clear(rx);
        return "clear sussese";
    }

    //判断缓存中的数据是否存在
    @GetMapping("/exists")
    public String exists(){
      boolean result= cacheChannel.exists(rx,key);
      return "exists:"+result;
    }

    //判断数据从哪一级获取
    @GetMapping("/check")
    public String check(){
       int level = cacheChannel.check(rx,key);
        return "level:"+level;
    }
}
